import React, { createContext, useContext, useState, ReactNode } from 'react';
import { useApiSettings } from './ApiSettingsContext';
import { RetrievalService, RetrievalResult, RetrievalRequest } from '../services/RetrievalService';

export interface SearchParameters {
  similarityThreshold: number;
  topK: number;
  hybridSearch: boolean;
  keywordWeight: number;
  reranking: string;
}

interface RetrievalContextType {
  searchResults: RetrievalResult[];
  loading: boolean;
  performSearch: (query: string, compareMode?: boolean) => Promise<void>;
  searchParams: SearchParameters;
  updateSearchParams: (key: keyof SearchParameters, value: any) => void;
  previousResults: RetrievalResult[];
  clearResults: () => void;
}

const defaultSearchParams: SearchParameters = {
  similarityThreshold: 0.7,
  topK: 10,
  hybridSearch: false,
  keywordWeight: 0.3,
  reranking: 'none',
};

const RetrievalContext = createContext<RetrievalContextType | undefined>(undefined);

export const RetrievalProvider: React.FC<{children: ReactNode}> = ({ children }) => {
  const [searchResults, setSearchResults] = useState<RetrievalResult[]>([]);
  const [previousResults, setPreviousResults] = useState<RetrievalResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState<SearchParameters>(defaultSearchParams);
  const { apiSettings } = useApiSettings();

  // 构建检索服务实例（需确保API设置有效）
  const getRetrievalService = () => {
    try {
      return new RetrievalService();
    } catch (error) {
      console.error("Failed to create RetrievalService:", error);
      throw new Error("无法初始化检索服务，请检查API设置");
    }
  };

  const updateSearchParams = (key: keyof SearchParameters, value: any) => {
    setSearchParams(prev => ({
      ...prev,
      [key]: value
    }));
  };

  const clearResults = () => {
    setSearchResults([]);
    setPreviousResults([]);
  };

  const performSearch = async (query: string, compareMode = false) => {
    if (!query.trim()) return;
    setLoading(true);
    
    try {
      // 验证API密钥
      if (!apiSettings.embedding.apiKey || !apiSettings.retrieval.apiKey) {
        throw new Error("请先配置Embedding服务和检索服务API密钥");
      }
      
      const retrievalService = getRetrievalService();
      
      // 构建检索请求
      const request: RetrievalRequest = {
        query,
        topK: searchParams.topK,
        similarityThreshold: searchParams.similarityThreshold,
        hybridSearch: searchParams.hybridSearch,
        includeVectors: true,  // 用于可视化
        namespace: apiSettings.retrieval.namespace
      };
      
      // 如果是比较模式，保存当前结果作为之前的结果
      if (compareMode && searchResults.length > 0) {
        setPreviousResults(searchResults);
      }
      
      // 执行检索
      const results = await retrievalService.search(request);
      setSearchResults(results);
    } catch (error) {
      console.error('Error performing search:', error);
      // 这里可以添加错误提示
    } finally {
      setLoading(false);
    }
  };

  return (
    <RetrievalContext.Provider
      value={{
        searchResults,
        loading,
        performSearch,
        searchParams,
        updateSearchParams,
        previousResults,
        clearResults
      }}
    >
      {children}
    </RetrievalContext.Provider>
  );
};

export const useRetrievalContext = () => {
  const context = useContext(RetrievalContext);
  if (context === undefined) {
    throw new Error('useRetrievalContext must be used within a RetrievalProvider');
  }
  return context;
}; 